Spring Cloud—三、使用Spring Cloud实现微服务

Author Avatar
zuoqy 11月 14, 2018
  • 在其它设备中阅读本文章

业务:
1.商品微服务:通过商品id查询商品的服务。
2.订单微服务:创建订单时,通过调用商品的微服务进行查询商品数据。
业务.png

说明:
1.对于商品微服务而言,商品微服务是服务的提供者,订单微服务是服务的消费者。
2.对于订单微服务而言,订单微服务是服务的提供者,人是服务的消费者。

3.1、实现商品微服务

3.1.1、创建工程

创建工程.png

3.1.2、导入依赖
1
2
3
4
5
6
7
8
9
10
11
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.1.3、创建实体Item
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package cn.zuoqy.springclouddemoitem.model;

/**
* Created by zuoqy on 14:05 2018/10/22.
*/
public class Item {

private Long id;
private String title;
private String pic;
private Long price;

public Item(){};

public Item(Long id, String title, String pic, Long price) {
this.id = id;
this.title = title;
this.pic = pic;
this.price = price;
}
}
3.1.4、编写ItemService

编写itemService用于实现具体的商品查询逻辑,为了方便,我们并不真正的连接数据库,而是做模拟实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.zuoqy.springclouddemoitem.service;

import cn.zuoqy.springclouddemoitem.model.Item;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
* Created by zuoqy on 14:10 2018/10/22.
*/
@Service
public class ItemService {

public Item queryItemById(Long id) {
return MAP.get(id);
}

private static final Map<Long, Item> MAP = new HashMap<>();

static {
MAP.put(1L,new Item(1L, "商品标题1", "http://图片1", 100L));
MAP.put(2L,new Item(2L, "商品标题2", "http://图片2", 100L));
MAP.put(3L,new Item(3L, "商品标题3", "http://图片3", 100L));
MAP.put(4L,new Item(4L, "商品标题4", "http://图片4", 100L));
MAP.put(5L,new Item(5L, "商品标题5", "http://图片5", 100L));
MAP.put(6L,new Item(6L, "商品标题6", "http://图片6", 100L));
}
}

3.1.5、编写ItemController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package cn.zuoqy.springclouddemoitem.controller;

import cn.zuoqy.springclouddemoitem.model.Item;
import cn.zuoqy.springclouddemoitem.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by zuoqy on 14:16 2018/10/22.
*/
@RestController
@RequestMapping(value = "item")
public class ItemController {

@Autowired
private ItemService itemService;

/**
* 对外提供接口服务,查询商品信息
*/
@GetMapping(value = "query/{id}")
public Item queryItemById(@PathVariable("id") Long id) {
return itemService.queryItemById(id);
}
}

@RestController注解说明:RestController注解.png
从源码可以看出,这是一个组合注解,组合了@Controller和Response注解。相当于我们同时写了这2个注解。
@GetMapping注解说明:
GetMapping注解.png
@GetMapping注解是@RequestMapping(method=RequestMethod.GET)简写方式。其功能都是一样的。
同理还有其它注解:@DeleteMapping,@PostMapping,@PutMapping...

3.1.6、编写application.properties文件

spring Boot以及spring Cloud项目支持ymlproperties格式的配置文件。
yml格式是YAML(Yet Another Markup Language)编写的格式,YAML和properties格式的文件是相互转化的。如:

1
2
Server:
prot:18100

等价于

1
server.port=18100

配置文件的示例:application.properties.png

3.1.7、启动程序测试

测试结果.png

3.2、实现订单微服务

3.2.1、创建工程springcloud-demo-order (同3.1.1)
3.2.2、导入依赖 (同3.1.2)
3.2.3、创建Order实体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package cn.zuoqy.springclouddemoorder.model;

import java.util.Date;
import java.util.List;

/**
* Created by zuoqy on 14:29 2018/10/22.
*/
public class Order {

private String orderId;
private Long userId;
private Date createDate;
private Date updateDate;
private List<OrderDetail> orderDetailList;

public Order() {}

public Order(String orderId, Long userId, Date createDate, Date updateDate, List<OrderDetail> orderDetailList) {
this.orderId = orderId;
this.userId = userId;
this.createDate = createDate;
this.updateDate = updateDate;
this.orderDetailList = orderDetailList;
}
}
3.2.4、创建订单详情OrderDetail实体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package cn.zuoqy.springclouddemoorder.model;

/**
* Created by zuoqy on 14:29 2018/10/22.
*/
public class OrderDetail {

private String orderId;

private Item item = new Item();

private OrderDetail() {}

public OrderDetail(String orderId, Item item) {
this.orderId = orderId;
this.item = item;
}
}
3.2.5、将商品微服务中的Item类拷贝到当前工程

Item.png

3.2.6、编写ItemService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package cn.zuoqy.springclouddemoorder.service;

import cn.zuoqy.springclouddemoorder.model.Item;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
* Created by zuoqy on 14:43 2018/10/22.
*/
@Service
public class ItemService {

@Autowired
private RestTemplate restTemplate;

public Item queryItemById(Long id) {
return this.restTemplate.getForObject("http://127.0.0.1:8081/item/"+id,Item.class);
}
}
3.2.7、编写OrderService

该Service实现的根据订单Id查询订单的服务,为了方便测试,我们将构造数据实现,不采用查询数据库的方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package cn.zuoqy.springclouddemoorder.service;

import cn.zuoqy.springclouddemoorder.model.Item;
import cn.zuoqy.springclouddemoorder.model.Order;
import cn.zuoqy.springclouddemoorder.model.OrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* Created by zuoqy on 14:34 2018/10/22.
*/
@Service
public class OrderService {

@Autowired
private ItemService itemService;

/**
* 根据订单id查询订单数据
*/
public Order queryOrderById(String orderId) {
Order order = MAP.get(orderId);
if (null == order) {
return null;
}
List<OrderDetail> orderDetails = order.getOrderDetailList();
for (OrderDetail orderDetail: orderDetails) {
Item item = this.itemService.queryItemById(orderDetail.getItem().getId());
if (null == item) continue;
orderDetail.setItem(item);
}
return order;
}


private static final Map<String, Order> MAP = new HashMap<>();

static {
Order order = new Order();
order.setOrderId("9527order");
order.setCreateDate(new Date());
order.setUpdateDate(new Date());
order.setUserId(9527L);
List<OrderDetail> orderDetails = new ArrayList<>();
Item item = new Item();
item.setId(2L);
orderDetails.add(new OrderDetail(order.getOrderId(),item));
Item item2 = new Item();
item2.setId(3L);
orderDetails.add(new OrderDetail(order.getOrderId(),item2));
order.setOrderDetailList(orderDetails);
MAP.put(order.getOrderId(),order);
}
}

3.2.8、编写OrderController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package cn.zuoqy.springclouddemoorder.controller;

import cn.zuoqy.springclouddemoorder.model.Order;
import cn.zuoqy.springclouddemoorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by zuoqy on 14:56 2018/10/22.
*/
@RestController
@RequestMapping(value = "order")
public class OrderController {

@Autowired
private OrderService orderService;

@GetMapping(value = "/query/{orderId}")
public Order queryOrderById(@PathVariable("orderId") String orderId) {
return orderService.queryOrderById(orderId);
}
}
3.2.9、向Spring容器中定义RestTemplate对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package cn.zuoqy.springclouddemoorder;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class SpringcloudDemoOrderApplication {

public static void main(String[] args) {
SpringApplication.run(SpringcloudDemoOrderApplication.class, args);
}

@Bean //向Spring容器中定义RestTemplate对象
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
3.2.10、编写application.properties

application.properties.png

3.2.11、启动测试

测试结果.png

3.3、添加okHttp的支持

okhttp是一个封装URL,比HttpClient更友好易用的工具。目前似乎okhttp更流行一些。
官网:http://square.github.io/okhttp/
okhttp.png
RestTemplate底层默认使用的jdk的标准实现,如果我们想让RestTemplate的底层使用okhttp非常简单:
1.添加okhttp依赖

1
2
3
4
5
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.0</version>
</dependency>

2.设置requestFactory

1
2
3
4
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}

测试结果与之前一样。

3.4、解决订单系统中的url硬编码问题

通过以上的测试我们发现,在订单系统中要调用商品微服务中的查询接口来获取数据,在订单微服务中将url硬编码到代码中,这样显然不好,因为,运行环境一旦发生变化这个url地址将不可用。

解决方案:将url地址写入到application.properties配置文件中。
实现:修改appcation.properties文件:
appcation.properties.png
修改ItemService中的实现:
ItemService.png


出自:zuoqy博客
如若转载请注明出处!